﻿using System;
using System.IO;
using System.Linq;

namespace blackhouse.WebNemo.Business.Groups {
    public class RecordFile {

        #region Fields

        private readonly int groupId;
        private readonly string column;
        private readonly int recordId;
        private RecordFileOperation fileOperation;
        private bool lazzyLoaded;
        private RecordFileData data;

        #endregion

        #region Properties

        private RecordFileOperation FileOperation {
            get {
                return this.fileOperation ??
                       (this.fileOperation = RecordFileOperation.Get(this.groupId, this.column, this.recordId));
            }
        }

        public string FileName {
            get {
                this.EnsureFileDataLoaded();
                return this.data.FileName;
            }
        }

        public Guid FileGuid {
            get {
                this.EnsureFileDataLoaded();
                return this.data.Hash;
            }
        }

        public long FileSize {
            get {
                this.EnsureFileDataLoaded();
                return this.data.Size;
            }
        }

        public bool Exist {
            get {
                this.EnsureFileDataLoaded();
                return this.data.Exist;
            }
        }


        #endregion

        #region Constructors

        public RecordFile(IGroupRecord record, string column)
            : this(record.BelongsToGroupId, column, record.RecordId) {
        }

        public RecordFile(int groupId, string column, int recordId) {
            this.groupId = groupId;
            this.column = column;
            this.recordId = recordId;
        }

        #endregion

        #region Methods

        private void EnsureFileDataLoaded() {
            if (this.lazzyLoaded) return;
            this.data = this.FileOperation.GetInfo();
            this.lazzyLoaded = true;
        }

        public bool SaveFile(string fileName, Stream fileStream) {
            var recordFileData = new RecordFileData
            {
                FileName = FormatFileName(fileName),
                Size = fileStream.Length,
                Hash = Guid.NewGuid(),
                Exist = false
            };
            return this.FileOperation.SaveFile(recordFileData, fileStream);
        }

        private static string FormatFileName(string oryginalFileName) {
            var extension = oryginalFileName.Split('.').Last();
            oryginalFileName = oryginalFileName.ReplaceEx("." + extension, "").CleanStringForUrl().RemovePolishChars().RemovePunctuation() + "." + extension;
            return oryginalFileName;
        }

        public byte[] GetData() {
            return this.FileOperation.GetFileData();
        }

        #endregion

    }
}
